Categories
React Tips

React Tips — Clicks, Watching Widths, Custom Links

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Manually Trigger Click Event in React

To manually trigger a click event in a React component, we can assign a ref to the DOM element.

And then we can call click on the ref.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  render() {
    return (
      <div onClick={this.handleClick}>
        <input ref={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick(e){
    this.inputElement.click();
  }
}

We have assigned the inputElement ref with a callback.

Then we click the input element in the handleClick method by calling click on the this.inputElement DOM object.

This also works in a function component:

const UploadsWindow = () => {
  const inputRef = useRef();

  const uploadClick = e => {
    e.preventDefault();
    inputRef.current.click();
  };

  return (
    <>
      <input
        type="file"
        name="fileUpload"
        ref={inputRef}
        multiple
        onClick={uploadClick}
      />
    </>
  )
}

We created a ref with the useRef hook and assigned it to the input.

Then, we have the click handler uploadClick function, which calls the click method on the input DOM element.

The current property has the DOM object that’s been assigned the ref.

Respond to the Width of an Auto-Sized DOM Element in React

To watch the width of the DOM elemnt on React, we can use the react-measure package.

To install it, we run:

yarn add react-measure

or:

npm install react-measure --save

Then we use it by writing:

import * as React from 'react'
import Measure from 'react-measure'

const Width = () => (
  <Measure bounds>
    {({ measureRef, contentRect: { bounds: { width }} }) => (
      <div ref={measureRef}>{width}</div>
    )}
  </Measure>
)

We have the Measure component, which has a callback with many properties as its parameter.

measureRef is a ref that we can use to get the element.

contentRect has the information about the element that’s been assigned to the measureRef .

width has the width.

So we watch the element’s width changes with the width property.

There’s also the react-sizeme component that can also be used to get the size of the component.

For instance, we can write:

import SizeMe from 'react-sizeme';

class Circle extends Component {
  render() {
    const { width, height } = this.props.size;

    return (
     <svg width="100" height="100">
       <circle cx="150" cy="100" r="80" fill="green" />
     </svg>
    );
  }
}

export default SizeMe()(Circle);

It comes with the SizeMe higher-order component, which we can pass our component into it to get the width and height of it.

They’re available via the props since we called the SizeMe higher-order component with it.

React Context Outside of Render Function

With a function component, we can use the useContext hook to let us access the context anywhere in our component.

For instance, we can write:

const App = () => {
  const contextValue = useContext(AppContext);
  // ...
}

In a class component, we can set the static contextTyoe property so that we can use the context anywhere in our class component.

We access the context with the this.context property.

For instance, we can write:

class App extends React.Component {
  componentDidMount() {
    const value = this.context;
  }

  componentDidUpdate() {
    const value = this.context;
    /* ... */
  }

  componentWillUnmount() {
    const value = this.context;
    /* ... */
  }

  render() {
    const value = this.context;
    /* render content */
  }
}

App.contextType = AppContext;

this.context is available anywhere once we set the contextType property to a context.

Wrapping a React Router Link in an HTML Button

We can wrap the Link component with anything we want to display.

For example, we can write:

<Link to="/profile">
   <button type="button">
     click me
   </button>
 </Link>

We can also embed components:

<Link to="/profile">
   <Button>
     click me
   </Button>
 </Link>

Conclusion

We can trigger the click event by assigning an element to a ref and calling methods on it.

Also, we can use contexts outside of the render function.

There’re libraries that let us watch for changes in the dimension of a component.

React Router Link components can have elements or components inside it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *